/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.data.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import edu.cmu.lti.sepia.infra.topic.model.Nugget;
import edu.cmu.lti.sepia.util.ServletUtil;


/**
 * 
 * Manages Answer Nugget object in a DB.
 * 
 * @see Nugget
 * @author Hideki Shima
 *
 */
public class NuggetDAO {
	
	public static void addNugget( SQL sql, String table, Nugget nugget ) throws SQLException {
		String query = Query.generate( Query.ADD_NUGGET, table );
		
		PreparedStatement ps = sql.getConnection().prepareStatement(query);

		ps.setInt(1, nugget.getTopicId());
		ps.setString(2, nugget.getText());
		ps.setInt(3, nugget.isSimilar()?1:0);
		sql.executeInSilence(ps);
		ps.close();
	}
	
	public static void addNuggets( SQL sql, String table, List<Nugget> nuggets ) throws SQLException {
    if ( nuggets!=null ) {
      for ( Nugget nugget : nuggets ) {
        NuggetDAO.addNugget(sql, table, nugget );
      }
    }
	}
	
	public static void deleteNugget( SQL sql, String table, int nuggetId ) throws SQLException {
		String query = Query.generate( Query.DELETE_NUGGET, table );
		
		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		ps.setInt(1, nuggetId);
		sql.execute(ps);
		ps.close();
	}
	
	public static void deleteNuggetsByTopicId( SQL sql, String table, int topicId ) throws SQLException {
		String query = Query.generate( Query.DELETE_NUGGET_BYTOPIC, table );
		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		ps.setInt(1, topicId);
		sql.execute(ps);
		ps.close();
	}
	
	public static List<Nugget> findByTopicId( SQL sql, String table, int topicId ) throws SQLException {
	  String query = Query.generate( Query.FIND_NUGGET, table );
	  PreparedStatement ps = sql.getConnection().prepareStatement(query);
	  ResultSet rs = null;
	  
	  List<Nugget> nuggets = new ArrayList<Nugget>();
	  ps.setInt(1, topicId);
	  rs = sql.executeSelect(ps);
	  
	  while ( rs.next() ) nuggets.add( rsToObject(rs) );
	  
	  rs.close();
	  ps.close();
	  
	  VoteDAO.loadVotes( sql, table, topicId, nuggets );
	  
	  return nuggets;
	}
	
	private static Nugget rsToObject( ResultSet rs ) throws SQLException {
		Nugget nugget = new Nugget( rs.getInt(1), rs.getInt(2), 
				rs.getString(3), rs.getInt(4)==1 );
		return nugget;
	}
	
  public static JSONArray convertNuggets( List<Nugget> nuggets ) throws JSONException {
    JSONArray jsonArray = new JSONArray();
    if ( nuggets!=null ) {
      for ( Nugget n : nuggets ) {
        JSONObject j = new JSONObject();
        j.put("nuggetId", n.getNuggetId());
        j.put("answerNugget", n.getText());
        j.put("isSimilar", (n.isSimilar()?1:0));
        
        // votes available only for similar nuggets
        if (!n.isSimilar()) {
          j.put("votes", VoteDAO.convertVotes( n.getVotes() ));
        }
        jsonArray.put(j);
      }
    }
    return jsonArray;
  }
   
  public static Nugget parseRequest( HttpServletRequest request ) {
    if ( request.getParameter("nuggetId")==null &&
        request.getParameter("answerNugget")==null ) return null;
    
    ServletUtil s = new ServletUtil( request );
    
    return new Nugget( 
        s.readInt("nuggetId", 0),
        s.readInt("topicId", 0),
        s.readString("answerNugget", ""),
        s.readInt("isSimilar", 0)==1
    );
  }
    
}
